package kevin.framework.basic.common.user;

import java.util.Date;

import kevin.framework.basic.exception.FrameException;
import net.rubyeye.xmemcached.MemcachedClient;

/**
 * @ClassName: MemcachedUserContext
 * @Description: 利用memcached实现分布式或者集中式登录用户保存，用于分布式系统部署
 * @author kevin.huang
 * @date 2016年1月16日 上午8:00:37
 */
public class MemcachedUserContext extends LoginUserContext implements ILoginUserContext {

	private MemcachedClient memcachedClient;

	/**
	 * 可利用spring注入客户端
	 ***/
	public void setMemcachedClient(MemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	/***
	 * 过期时间，可注入
	 ***/
	@Override
	public void setExpiry(int expiry) {
		this.expiry = expiry;
	}

	@Override
	public int getExpiry() {
		return this.expiry;
	}

	@Override
	public void setUpdateRate(int rate) {
		this.updateRate = rate;
	}

	/***
	 * 实现登录session的平滑延时
	 ***/
	@Override
	public void updateExpiry(String key) throws Exception {
		LoginUser user = memcachedClient.get(key);
		if (user != null) {
			Date lsTime = user.getSessionTime();
			Date now = new Date();
			long diff = now.getTime() - lsTime.getTime();
			long min = diff / (1000 * 60);
			long flag = this.expiry / this.updateRate;
			if (min >= flag) {
				user.setSessionTime(now);
				memcachedClient.replace(key, this.expiry * 60, user);
			}
		}
	}

	@Override
	public String setLoginUser(LoginUser user) throws Exception {
		// int exp = this.expiry * 60;
		// memcachedClient.add(key, exp, user);
		return "";
	}

	@Override
	public void logout() throws Exception {
		String key = getLoginKeyFromRequest();
		if (key != null) {
			memcachedClient.deleteWithNoReply(key);
		}

	}

	@Override
	public void setKeyValue(String key, Object obj) throws Exception {
		int exp = this.expiry * 60;
		memcachedClient.add(key, exp, obj);
	}

	@Override
	public Object getKeyValue(String key) throws Exception {
		return memcachedClient.get(key);
	}

	@Override
	public LoginUser getCurrentUser() throws Exception {
		String key = getLoginKeyFromRequest();
		if (key == null) {
			return null;
		}

		Object obj = this.getKeyValue(key);
		if (obj == null) {
			return null;
		}

		return (LoginUser) obj;
	}

	@Override
	public void deleteKeyValue(String key) throws Exception {
		memcachedClient.delete(key);
	}

	@Override
	public void logout(String sessionId) throws Exception {
		// TODO Auto-generated method stub

	}

}
